import time
from config.config import get_config
from fastapi import UploadFile, HTTPException
import os
import re
import zipfile
import shutil

async def bash_lh(source: str, to: str, file: UploadFile):
  conf = get_config(to)
  if isinstance(conf, dict):
    savePath = conf.get('savePath')
    tarPath = conf.get('tarPath')
    savePath = savePath.replace("\\", "/", -1)
    tarPath = tarPath.replace("\\", "/", -1)
    if not os.path.exists(savePath):
      os.mkdir(savePath, 0o775)
    files = os.listdir(savePath)
    list = []
    if os.path.isfile(f"{savePath}/{file.filename}"):
      os.remove(f"{savePath}/{file.filename}")
      print(f"已删除重名文件{savePath}/{file.filename}")
    else:
      print(f"文件{savePath}/{file.filename}不存在", source)
    for name in files:
      if len(re.compile('.(zip|tar)').findall(name)) > 0:
        list.append(name)
    if len(list) > 10:
      list = sorted(list)
    data = list[0:len(list) - 10]
    for name in data:
      if os.path.isfile(f"{savePath}/{name}"):
        os.remove(f"{savePath}/{name}")
        print(f"已删除多余备份文件{savePath}/{name}")
      else:
        print(f"文件{savePath}/{name}不存在")
    with open(f"{savePath}/{file.filename}", 'wb') as buffer:
      content = await file.read(file.size)
      buffer.write(content)
      if os.path.exists(tarPath):
        shutil.rmtree(tarPath)
    os.mkdir(tarPath, 0o775)
    with zipfile.ZipFile(f"{savePath}/{file.filename}", 'r') as zip_ref:
      zip_ref.extractall(tarPath)
      return "部署成功"
  else:
    raise HTTPException(status_code=500, detail="发布配置源未查到运维配置命令")
